module Message
  TYPES = {
    :REQUEST => 0,
    :GRANT => 1,
    :ZOMBIE => 2,
    :HELLO => 3,
    :PING => 4,
    :OK => 5,
  }

  def self.reverse id
    TYPES.rassoc(Integer(id)).first rescue nil
  end

  def self.const_missing(name)
    TYPES[name]
  end

  def self.const_get(name)
    if TYPES[name] then
      TYPES[name]
    else 
      name
    end
  end

  def self.pack msg, id, clock
    [self.const_get(msg), id, clock].join(':')
  end
  
  def self.unpack message
    part = message.split ':'
    type = Message::reverse(part[0])
    type = type.to_sym if type
    id = Integer(part[1])
    clock = Integer(part[2])
    return type, id, clock
  end
end
